package org.douxiaoban.client.adapter;

import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import org.douxiaoban.client.R;
import org.douxiaoban.client.api.UserInfoData;
import org.douxiaoban.client.app.Assistant;
import org.douxiaoban.client.util.ThreadTool;

import java.util.ArrayList;

public class UsersAdapter extends DoubanAdapter{
	
	private Handler m_handler = new Handler(){
		@Override
		public void handleMessage(Message msg){
			Bundle bundle = msg.getData();
			switch(msg.what){
				case Assistant.TOOLS_MSG_AVATAR:
					updateAvatar(bundle);
					break;
				default:
					break;
			}
			super.handleMessage(msg);
		}
	};
	
	public UsersAdapter(Context context){
		super(context, new ArrayList<UserInfoData>());
	}
	
	
	@Override
	public View getView(int position, View view, ViewGroup vGroup){
		if(position > this.getCount()){
			return null;
		}
		LayoutInflater flater = LayoutInflater.from(mContext);
		view = flater.inflate(R.layout.user_info_item, null);
		
		ImageView avatar = (ImageView)view.findViewById(R.id.userItem_avatar);
		TextView  name	 = (TextView)view.findViewById(R.id.userItem_name);
		TextView  signature = (TextView)view.findViewById(R.id.userItem_signature);
		TextView location = (TextView)view.findViewById(R.id.userItem_location);
				
		UserInfoData data = (UserInfoData)mList.get(position);
		if(data.mSignature != null){
			signature.setText(data.mSignature);
		}else{
			signature.setVisibility(View.GONE);
		}
		name.setText(data.mName);
		
		if(data.mLocation.equals("null")){
			location.setVisibility(View.GONE);
		}else{
			location.setText(data.mLocation);
		}
		
		
		if(null == data.mAvatar){
			ThreadTool.instace(mContext).
						getAvatar(data.mId, data.mImageUrl, m_handler, position);
		}else{
			avatar.setImageBitmap(data.mAvatar);
		}
		return view;
	}
	/**
	 * 更新头像
	 * @param bundle
	 */
	private void updateAvatar(Bundle bundle){
		ThreadTool.ImageSerialz serialz;
		serialz = (ThreadTool.ImageSerialz)bundle.getSerializable(Assistant.TOOLS_KEY_AVATAR);
		UserInfoData item = (UserInfoData)mList.get(serialz.m_iPosition);
		item.mAvatar = serialz.m_bitmap;
		this.notifyDataSetChanged();
	}
}
	

